<template>
  <div class="permission-control">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <div class="header-left">
         <h1 class="page-title">权限管理</h1>
         <p class="page-description">角色与权限管理</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" :icon="Plus" @click="showCreateRoleDialog">
          新增角色
        </el-button>
        <el-button :icon="Refresh" @click="refreshRoles">刷新</el-button>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="permission-main">
      <!-- 左侧角色列表 -->
      <div class="roles-panel">
        <div class="panel-header">
          <h3 class="panel-title">角色列表</h3>
          <el-input
            v-model="roleSearchKeyword"
            placeholder="搜索角色..."
            prefix-icon="Search"
            size="small"
            style="width: 200px;"
            clearable
          />
        </div>
        
        <div class="roles-list">
          <div 
            v-for="role in filteredRoles" 
            :key="role.id"
            class="role-item"
            :class="{ active: selectedRole?.id === role.id }"
            @click="selectRole(role)"
          >
            <div class="role-info">
              <div class="role-name">{{ role.name }}</div>
              <div class="role-description">{{ role.description }}</div>
              <div class="role-meta">
                <el-tag :type="role.isSystem ? 'info' : 'primary'" size="small">
                  {{ role.isSystem ? '系统角色' : '自定义角色' }}
                </el-tag>
                <span class="user-count">{{ role.userCount }} 用户</span>
              </div>
            </div>
            <div class="role-actions">
              <el-button 
                type="primary" 
                :icon="Edit" 
                size="small" 
                @click.stop="editRole(role)"
                :disabled="role.isSystem"
              />
              <el-button 
                type="danger" 
                :icon="Delete" 
                size="small" 
                @click.stop="deleteRole(role)"
                :disabled="role.isSystem"
              />
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧权限配置区域 -->
      <div class="permissions-panel">
        <div class="panel-header" v-if="selectedRole">
          <h3 class="panel-title">
            {{ selectedRole.name }} - 权限配置
          </h3>
          <div class="header-actions">
            <el-button 
              type="success" 
              :icon="Check" 
              @click="savePermissions"
              :loading="saving"
            >
              保存权限
            </el-button>
            <el-button @click="resetPermissions">重置</el-button>
          </div>
        </div>

        <div v-if="!selectedRole" class="empty-state">
          <el-empty description="请选择一个角色来配置权限" />
        </div>

        <div v-else class="permissions-config">
          <!-- 功能模块权限 -->
          <div class="permission-section">
            <h4 class="section-title">
              <el-icon><Setting /></el-icon>
              功能模块权限
            </h4>
            
            <div class="permission-matrix">
              <div class="matrix-header">
                <div class="module-name">功能模块</div>
                <div class="permission-type">查看</div>
                <div class="permission-type">编辑</div>
                <div class="permission-type">审核</div>
                <div class="permission-type">发布</div>
              </div>
              
              <div 
                v-for="module in modulePermissions" 
                :key="module.id"
                class="matrix-row"
              >
                <div class="module-name">
                  <el-icon><component :is="module.icon" /></el-icon>
                  {{ module.name }}
                </div>
                <div class="permission-type">
                  <el-switch 
                    v-model="module.permissions.view"
                    @change="updatePermission(module.id, 'view', $event)"
                  />
                </div>
                <div class="permission-type">
                  <el-switch 
                    v-model="module.permissions.edit"
                    @change="updatePermission(module.id, 'edit', $event)"
                    :disabled="!module.permissions.view"
                  />
                </div>
                <div class="permission-type">
                  <el-switch 
                    v-model="module.permissions.audit"
                    @change="updatePermission(module.id, 'audit', $event)"
                    :disabled="!module.permissions.edit"
                  />
                </div>
                <div class="permission-type">
                  <el-switch 
                    v-model="module.permissions.publish"
                    @change="updatePermission(module.id, 'publish', $event)"
                    :disabled="!module.permissions.audit"
                  />
                </div>
              </div>
            </div>
          </div>

           <!-- 数据访问权限 -->
           <div class="permission-section">
             <h4 class="section-title">
               <el-icon><DataBoard /></el-icon>
               数据访问权限
             </h4>
             
             <div class="data-permissions">
               <div class="permission-group">
                 <div class="group-title">工单数据权限</div>
                 <div class="permission-options">
                   <el-checkbox-group v-model="dataPermissions.tickets">
                     <el-checkbox label="view_all">查看所有工单</el-checkbox>
                     <el-checkbox label="view_assigned">查看分配给自己的工单</el-checkbox>
                     <el-checkbox label="view_department">查看本部门工单</el-checkbox>
                     <el-checkbox label="create">创建工单</el-checkbox>
                     <el-checkbox label="edit">编辑工单</el-checkbox>
                     <el-checkbox label="comment">评论工单</el-checkbox>
                     <el-checkbox label="download">下载附件</el-checkbox>
                     <el-checkbox label="delete">删除工单</el-checkbox>
                   </el-checkbox-group>
                 </div>
               </div>
               
               <div class="permission-group">
                 <div class="group-title">用户管理权限</div>
                 <div class="permission-options">
                   <el-checkbox-group v-model="dataPermissions.users">
                     <el-checkbox label="view">查看用户信息</el-checkbox>
                     <el-checkbox label="create">创建用户</el-checkbox>
                     <el-checkbox label="edit">编辑用户</el-checkbox>
                     <el-checkbox label="delete">删除用户</el-checkbox>
                     <el-checkbox label="assign_role">分配角色</el-checkbox>
                     <el-checkbox label="reset_password">重置密码</el-checkbox>
                   </el-checkbox-group>
                 </div>
               </div>
               
               <div class="permission-group">
                 <div class="group-title">内容管理权限</div>
                 <div class="permission-options">
                   <el-checkbox-group v-model="dataPermissions.content">
                     <el-checkbox label="view">查看内容</el-checkbox>
                     <el-checkbox label="edit">编辑内容</el-checkbox>
                     <el-checkbox label="review">审核内容</el-checkbox>
                     <el-checkbox label="publish">发布内容</el-checkbox>
                     <el-checkbox label="download">下载内容</el-checkbox>
                     <el-checkbox label="comment">评论内容</el-checkbox>
                   </el-checkbox-group>
                 </div>
               </div>
               
               <div class="permission-group">
                 <div class="group-title">系统管理权限</div>
                 <div class="permission-options">
                   <el-checkbox-group v-model="dataPermissions.system">
                     <el-checkbox label="config">系统配置</el-checkbox>
                     <el-checkbox label="backup">数据备份</el-checkbox>
                     <el-checkbox label="logs">查看日志</el-checkbox>
                     <el-checkbox label="monitor">系统监控</el-checkbox>
                     <el-checkbox label="security">安全设置</el-checkbox>
                   </el-checkbox-group>
                 </div>
               </div>
             </div>
           </div>

          <!-- 产品可见性控制 -->
          <div class="permission-section">
            <h4 class="section-title">
              <el-icon><View /></el-icon>
              产品可见性控制
            </h4>
            
            <div class="product-visibility">
              <div class="visibility-header">
                <span>选择该角色可以访问的系统模块：</span>
                <el-button-group size="small">
                  <el-button @click="selectAllProducts">全选</el-button>
                  <el-button @click="clearAllProducts">清空</el-button>
                </el-button-group>
              </div>
              
              <div class="product-grid">
                <div 
                  v-for="product in productModules" 
                  :key="product.id"
                  class="product-item"
                  :class="{ selected: product.visible }"
                  @click="toggleProduct(product.id)"
                >
                  <div class="product-icon">
                    <el-icon><component :is="product.icon" /></el-icon>
                  </div>
                  <div class="product-info">
                    <div class="product-name">{{ product.name }}</div>
                    <div class="product-description">{{ product.description }}</div>
                  </div>
                  <div class="product-status">
                    <el-icon v-if="product.visible" class="check-icon"><Check /></el-icon>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 创建/编辑角色对话框 -->
    <el-dialog
      v-model="showRoleDialog"
      :title="isEditRole ? '编辑角色' : '创建角色'"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleFormRules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
          />
        </el-form-item>
        
         <el-form-item label="基于模板">
           <el-select v-model="roleForm.template" placeholder="选择角色模板" style="width: 100%;">
             <el-option label="无模板" value="" />
             <el-option label="采集者模板" value="collector" />
             <el-option label="编辑者模板" value="editor" />
             <el-option label="管理者模板" value="manager" />
             <el-option label="超级管理员模板" value="super_admin" />
           </el-select>
         </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showRoleDialog = false">取消</el-button>
          <el-button type="primary" @click="handleRoleSubmit" :loading="submitting">
            {{ isEditRole ? '更新' : '创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, 
  Refresh, 
  Search, 
  Edit, 
  Delete, 
  Check, 
  Setting,
  DataBoard,
  View,
  Tickets,
  User,
  Lock,
  Document,
  Monitor,
  Download
} from '@element-plus/icons-vue'

console.log('权限控制组件加载')

// 响应式数据
const roleSearchKeyword = ref('')
const selectedRole = ref(null)
const saving = ref(false)
const submitting = ref(false)

// 对话框控制
const showRoleDialog = ref(false)
const isEditRole = ref(false)
const roleFormRef = ref()

// 角色表单
const roleForm = ref({
  name: '',
  description: '',
  template: ''
})

const roleFormRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '角色名称长度应在 2 到 20 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入角色描述', trigger: 'blur' },
    { max: 100, message: '描述长度不能超过 100 个字符', trigger: 'blur' }
  ]
}

// 角色列表数据
const rolesList = ref([
  {
    id: 1,
    name: '超级管理员',
    description: '拥有系统所有权限的最高级管理员角色',
    isSystem: true,
    userCount: 2,
    permissions: {}
  },
  {
    id: 2,
    name: '管理者',
    description: '具有管理权限，可以审核和发布内容，管理团队成员',
    isSystem: false,
    userCount: 8,
    permissions: {}
  },
  {
    id: 3,
    name: '编辑者',
    description: '具有编辑权限，可以创建和编辑内容，但需要审核后发布',
    isSystem: false,
    userCount: 15,
    permissions: {}
  },
  {
    id: 4,
    name: '采集者',
    description: '基础数据采集权限，可以查看和收集数据，提交给上级处理',
    isSystem: false,
    userCount: 32,
    permissions: {}
  }
])

// 模块权限配置
const modulePermissions = ref([
  {
    id: 'tickets',
    name: '工单管理',
    icon: 'Tickets',
    permissions: {
      view: true,
      edit: true,
      audit: false,
      publish: false
    }
  },
  {
    id: 'statistics',
    name: '统计分析',
    icon: 'DataBoard',
    permissions: {
      view: true,
      edit: false,
      audit: false,
      publish: false
    }
  },
  {
    id: 'permissions',
    name: '权限控制',
    icon: 'Lock',
    permissions: {
      view: false,
      edit: false,
      audit: false,
      publish: false
    }
  },
  {
    id: 'logs',
    name: '日志管理',
    icon: 'Document',
    permissions: {
      view: true,
      edit: false,
      audit: false,
      publish: false
    }
  }
])

// 数据权限配置
const dataPermissions = ref({
  tickets: ['view_assigned', 'create'],
  users: ['view'],
  content: ['view'],
  system: []
})

// 产品模块配置
const productModules = ref([
  {
    id: 'ticket-system',
    name: '工单系统',
    description: '工单管理和处理',
    icon: 'Tickets',
    visible: true
  },
  {
    id: 'statistics',
    name: '统计分析',
    description: '数据统计和分析报表',
    icon: 'DataBoard',
    visible: true
  },
  {
    id: 'permission-control',
    name: '权限管理',
    description: '角色和权限管理',
    icon: 'Lock',
    visible: false
  },
  {
    id: 'log-management',
    name: '日志管理',
    description: '系统操作日志',
    icon: 'Document',
    visible: false
  },
  {
    id: 'user-management',
    name: '用户管理',
    description: '用户账户和组织管理',
    icon: 'User',
    visible: false
  },
  {
    id: 'content-management',
    name: '内容管理',
    description: '内容创建、编辑和发布',
    icon: 'Edit',
    visible: false
  },
  {
    id: 'system-monitor',
    name: '系统监控',
    description: '系统状态和性能监控',
    icon: 'Monitor',
    visible: false
  },
  {
    id: 'data-export',
    name: '数据导出',
    description: '数据导出和备份功能',
    icon: 'Download',
    visible: false
  }
])

// 计算属性：筛选后的角色列表
const filteredRoles = computed(() => {
  if (!roleSearchKeyword.value) {
    return rolesList.value
  }
  
  const keyword = roleSearchKeyword.value.toLowerCase()
  return rolesList.value.filter(role => 
    role.name.toLowerCase().includes(keyword) ||
    role.description.toLowerCase().includes(keyword)
  )
})

// 页面初始化
onMounted(() => {
  console.log('权限控制页面初始化')
  // 默认选择第一个角色
  if (rolesList.value.length > 0) {
    selectRole(rolesList.value[0])
  }
})

// 刷新角色列表
const refreshRoles = async () => {
  console.log('刷新角色列表')
  
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    ElMessage.success('角色列表刷新成功')
  } catch (error) {
    console.error('刷新失败:', error)
    ElMessage.error('刷新失败，请重试')
  }
}

// 选择角色
const selectRole = (role) => {
  console.log('选择角色:', role.name)
  selectedRole.value = role
  
  // 加载角色权限配置
  loadRolePermissions(role)
}

// 加载角色权限配置
const loadRolePermissions = (role) => {
  console.log('加载角色权限:', role.name)
  
  // 根据角色类型设置不同的权限
  if (role.name === '超级管理员') {
    // 超级管理员拥有所有权限
    modulePermissions.value.forEach(module => {
      module.permissions = {
        view: true,
        edit: true,
        audit: true,
        publish: true
      }
    })
    
    dataPermissions.value = {
      tickets: ['all', 'create', 'delete'],
      users: ['view', 'create', 'edit', 'delete', 'assign'],
      system: ['config', 'backup', 'logs', 'monitor']
    }
    
    productModules.value.forEach(product => {
      product.visible = true
    })
  } else if (role.name === '管理者') {
    // 管理者角色权限
    modulePermissions.value.forEach(module => {
      if (module.id === 'tickets' || module.id === 'statistics') {
        module.permissions = { view: true, edit: true, audit: true, publish: true }
      } else if (module.id === 'permissions') {
        module.permissions = { view: true, edit: true, audit: false, publish: false }
      } else if (module.id === 'logs') {
        module.permissions = { view: true, edit: false, audit: false, publish: false }
      }
    })
    
    dataPermissions.value = {
      tickets: ['view_all', 'view_department', 'create', 'edit', 'comment', 'download'],
      users: ['view', 'create', 'edit', 'assign_role'],
      content: ['view', 'edit', 'review', 'publish', 'download', 'comment'],
      system: ['logs', 'monitor']
    }
    
    // 管理者可见大部分模块
    productModules.value.forEach(product => {
      product.visible = ['ticket-system', 'statistics', 'permission-control', 'log-management', 'user-management', 'content-management'].includes(product.id)
    })
  } else if (role.name === '编辑者') {
    // 编辑者角色权限
    modulePermissions.value.forEach(module => {
      if (module.id === 'tickets') {
        module.permissions = { view: true, edit: true, audit: false, publish: false }
      } else if (module.id === 'statistics') {
        module.permissions = { view: true, edit: false, audit: false, publish: false }
      } else {
        module.permissions = { view: false, edit: false, audit: false, publish: false }
      }
    })
    
    dataPermissions.value = {
      tickets: ['view_assigned', 'view_department', 'create', 'edit', 'comment', 'download'],
      users: ['view'],
      content: ['view', 'edit', 'download', 'comment'],
      system: []
    }
    
    // 编辑者可见基础模块
    productModules.value.forEach(product => {
      product.visible = ['ticket-system', 'statistics', 'content-management'].includes(product.id)
    })
  } else if (role.name === '采集者') {
    // 采集者角色权限（最基础权限）
    modulePermissions.value.forEach(module => {
      if (module.id === 'tickets') {
        module.permissions = { view: true, edit: false, audit: false, publish: false }
      } else {
        module.permissions = { view: false, edit: false, audit: false, publish: false }
      }
    })
    
    dataPermissions.value = {
      tickets: ['view_assigned', 'create', 'comment'],
      users: [],
      content: ['view', 'comment'],
      system: []
    }
    
    // 采集者只能访问基础模块
    productModules.value.forEach(product => {
      product.visible = ['ticket-system'].includes(product.id)
    })
  } else {
    // 其他角色的默认权限
    modulePermissions.value.forEach(module => {
      module.permissions = {
        view: module.id === 'tickets',
        edit: false,
        audit: false,
        publish: false
      }
    })
    
    dataPermissions.value = {
      tickets: ['view_assigned', 'create'],
      users: [],
      content: ['view'],
      system: []
    }
    
    // 默认只能访问工单系统
    productModules.value.forEach(product => {
      product.visible = product.id === 'ticket-system'
    })
  }
}

// 更新模块权限
const updatePermission = (moduleId, permissionType, value) => {
  console.log('更新权限:', moduleId, permissionType, value)
  
  const module = modulePermissions.value.find(m => m.id === moduleId)
  if (!module) return
  
  // 权限依赖逻辑
  if (permissionType === 'view' && !value) {
    // 取消查看权限时，自动取消所有其他权限
    module.permissions.edit = false
    module.permissions.audit = false
    module.permissions.publish = false
  } else if (permissionType === 'edit' && !value) {
    // 取消编辑权限时，自动取消审核和发布权限
    module.permissions.audit = false
    module.permissions.publish = false
  } else if (permissionType === 'audit' && !value) {
    // 取消审核权限时，自动取消发布权限
    module.permissions.publish = false
  } else if (permissionType === 'edit' && value) {
    // 开启编辑权限时，自动开启查看权限
    module.permissions.view = true
  } else if (permissionType === 'audit' && value) {
    // 开启审核权限时，自动开启查看和编辑权限
    module.permissions.view = true
    module.permissions.edit = true
  } else if (permissionType === 'publish' && value) {
    // 开启发布权限时，自动开启所有前置权限
    module.permissions.view = true
    module.permissions.edit = true
    module.permissions.audit = true
  }
}

// 保存权限配置
const savePermissions = async () => {
  console.log('保存权限配置')
  
  if (!selectedRole.value) {
    ElMessage.warning('请先选择一个角色')
    return
  }
  
  saving.value = true
  
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('权限配置保存成功')
  } catch (error) {
    console.error('保存权限失败:', error)
    ElMessage.error('保存权限失败，请重试')
  } finally {
    saving.value = false
  }
}

// 重置权限配置
const resetPermissions = () => {
  console.log('重置权限配置')
  
  if (!selectedRole.value) return
  
  ElMessageBox.confirm(
    '确定要重置当前角色的权限配置吗？',
    '重置确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    loadRolePermissions(selectedRole.value)
    ElMessage.success('权限配置已重置')
  }).catch(() => {
    console.log('用户取消重置')
  })
}

// 切换产品可见性
const toggleProduct = (productId) => {
  const product = productModules.value.find(p => p.id === productId)
  if (product) {
    product.visible = !product.visible
    console.log('切换产品可见性:', product.name, product.visible)
  }
}

// 全选产品
const selectAllProducts = () => {
  productModules.value.forEach(product => {
    product.visible = true
  })
  ElMessage.success('已选择所有产品模块')
}

// 清空产品选择
const clearAllProducts = () => {
  productModules.value.forEach(product => {
    product.visible = false
  })
  ElMessage.success('已清空产品模块选择')
}

// 显示创建角色对话框
const showCreateRoleDialog = () => {
  console.log('显示创建角色对话框')
  isEditRole.value = false
  roleForm.value = {
    name: '',
    description: '',
    template: ''
  }
  showRoleDialog.value = true
}

// 编辑角色
const editRole = (role) => {
  console.log('编辑角色:', role.name)
  isEditRole.value = true
  roleForm.value = {
    name: role.name,
    description: role.description,
    template: ''
  }
  showRoleDialog.value = true
}

// 删除角色
const deleteRole = async (role) => {
  console.log('删除角色:', role.name)
  
  try {
    const confirmed = await ElMessageBox.confirm(
      `确定要删除角色 "${role.name}" 吗？此操作不可恢复。`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'error'
      }
    )
    
    if (confirmed) {
      // 模拟删除操作
      const index = rolesList.value.findIndex(r => r.id === role.id)
      if (index > -1) {
        rolesList.value.splice(index, 1)
        
        // 如果删除的是当前选中的角色，重新选择
        if (selectedRole.value?.id === role.id) {
          selectedRole.value = rolesList.value.length > 0 ? rolesList.value[0] : null
          if (selectedRole.value) {
            loadRolePermissions(selectedRole.value)
          }
        }
        
        ElMessage.success('角色删除成功')
      }
    }
  } catch (error) {
    console.log('用户取消删除')
  }
}

// 处理角色表单提交
const handleRoleSubmit = async () => {
  if (!roleFormRef.value) return
  
  try {
    await roleFormRef.value.validate()
    
    submitting.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    if (isEditRole.value) {
      // 更新角色
      const role = rolesList.value.find(r => r.id === selectedRole.value.id)
      if (role) {
        role.name = roleForm.value.name
        role.description = roleForm.value.description
      }
      ElMessage.success('角色更新成功')
    } else {
      // 创建新角色
      const newRole = {
        id: Date.now(),
        name: roleForm.value.name,
        description: roleForm.value.description,
        isSystem: false,
        userCount: 0,
        permissions: {}
      }
      
      rolesList.value.push(newRole)
      ElMessage.success('角色创建成功')
    }
    
    showRoleDialog.value = false
    
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
.permission-control {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* 页面标题 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.header-left {
  flex: 1;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 8px 0;
}

.page-description {
  font-size: 14px;
  color: #6b7280;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
}

/* 主要内容区域 */
.permission-main {
  flex: 1;
  display: flex;
  gap: 24px;
  overflow: hidden;
}

/* 左侧角色面板 */
.roles-panel {
  width: 350px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.panel-header {
  padding: 20px;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.panel-title {
  font-size: 16px;
  font-weight: 600;
  color: #374151;
  margin: 0;
}

.roles-list {
  flex: 1;
  overflow-y: auto;
  padding: 12px;
}

.role-item {
  padding: 16px;
  border-radius: 8px;
  border: 1px solid #e5e7eb;
  margin-bottom: 12px;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.role-item:hover {
  border-color: #3b82f6;
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.1);
}

.role-item.active {
  border-color: #3b82f6;
  background: #eff6ff;
}

.role-info {
  flex: 1;
}

.role-name {
  font-size: 14px;
  font-weight: 600;
  color: #374151;
  margin-bottom: 4px;
}

.role-description {
  font-size: 12px;
  color: #6b7280;
  margin-bottom: 8px;
  line-height: 1.4;
}

.role-meta {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-count {
  font-size: 12px;
  color: #9ca3af;
}

.role-actions {
  display: flex;
  gap: 4px;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.role-item:hover .role-actions {
  opacity: 1;
}

/* 右侧权限面板 */
.permissions-panel {
  flex: 1;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.permissions-config {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.empty-state {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 权限配置区块 */
.permission-section {
  margin-bottom: 32px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #374151;
  margin: 0 0 16px 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 权限矩阵 */
.permission-matrix {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  overflow: hidden;
}

.matrix-header {
  background: #f9fafb;
  display: grid;
  grid-template-columns: 200px repeat(4, 1fr);
  border-bottom: 1px solid #e5e7eb;
}

.matrix-header .module-name,
.matrix-header .permission-type {
  padding: 12px 16px;
  font-size: 14px;
  font-weight: 600;
  color: #374151;
  border-right: 1px solid #e5e7eb;
}

.matrix-header .permission-type:last-child {
  border-right: none;
}

.matrix-row {
  display: grid;
  grid-template-columns: 200px repeat(4, 1fr);
  border-bottom: 1px solid #e5e7eb;
}

.matrix-row:last-child {
  border-bottom: none;
}

.matrix-row .module-name {
  padding: 16px;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #374151;
  border-right: 1px solid #e5e7eb;
}

.matrix-row .permission-type {
  padding: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-right: 1px solid #e5e7eb;
}

.matrix-row .permission-type:last-child {
  border-right: none;
}

/* 数据权限 */
.data-permissions {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.permission-group {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  overflow: hidden;
}

.group-title {
  background: #f9fafb;
  padding: 12px 16px;
  font-size: 14px;
  font-weight: 600;
  color: #374151;
  border-bottom: 1px solid #e5e7eb;
}

.permission-options {
  padding: 16px;
}

/* 产品可见性 */
.product-visibility {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.visibility-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  color: #374151;
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
}

.product-item {
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  gap: 12px;
}

.product-item:hover {
  border-color: #3b82f6;
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.1);
}

.product-item.selected {
  border-color: #10b981;
  background: #ecfdf5;
}

.product-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  background: #f3f4f6;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: #6b7280;
}

.product-item.selected .product-icon {
  background: #10b981;
  color: white;
}

.product-info {
  flex: 1;
}

.product-name {
  font-size: 14px;
  font-weight: 600;
  color: #374151;
  margin-bottom: 4px;
}

.product-description {
  font-size: 12px;
  color: #6b7280;
}

.product-status {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.check-icon {
  color: #10b981;
  font-size: 18px;
}

/* 对话框 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .permission-main {
    flex-direction: column;
  }
  
  .roles-panel {
    width: 100%;
    max-height: 300px;
  }
  
  .product-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
  }
  
  .panel-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .matrix-header,
  .matrix-row {
    grid-template-columns: 120px repeat(4, 1fr);
    font-size: 12px;
  }
  
  .visibility-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
}

/* 深色主题适配 */
@media (prefers-color-scheme: dark) {
  .roles-panel,
  .permissions-panel {
    background: #1f2937;
    border: 1px solid #374151;
  }
  
  .page-title,
  .panel-title,
  .section-title {
    color: #f9fafb;
  }
  
  .page-description {
    color: #d1d5db;
  }
  
  .role-item {
    border-color: #374151;
  }
  
  .role-item.active {
    background: #1e40af;
    border-color: #3b82f6;
  }
  
  .role-name {
    color: #f9fafb;
  }
  
  .role-description {
    color: #9ca3af;
  }
}
</style>
